const util = require("../../../utils/util.js");
const db = wx.cloud.database();
const _ = db.command
Page({
  data: {
    showTopTips: false,
    files: [],
    uploadImgArry: [],
    proName: '',
    proDetail: '',
    proNowPrice: '',
    proPrimePrice: '',
    proClassify: '',
    proDescription: '',
    uploadImgCount: 0,
    showGgNum: 0,
    proData: [],
    id: '',
    proGg:[],
    proYf:0,
    proPx:0,
    proState:true,
    proSale:0,
    newImgCount:0,
    proUnit:''
  },
  onLoad: function (options) {
    if (options.id == null || options.id == '') {
      this.setData({
        proGg : {pro:[],con:[]}
      })
    } else {
      this.data.id = options.id;
      db.collection('shop_product').where({
        _id: _.eq(options.id)
      }).get().then(res => {
        //TODO
        this.setData({
          id:options.id,
          proName: res.data[0].name,
          proNowPrice: res.data[0].price,
          proPrimePrice: res.data[0].price_org,
          proClassify: res.data[0].classify,
          proDescription: res.data[0].subname,
          proDetail: res.data[0].detail,
          files:res.data[0].img_url,
          proGg:res.data[0].gg,
          proYf:res.data[0].yf,
          proPx:res.data[0].px,
          proSale:res.data[0].sale,
          proState:res.data[0].state,
          proUnit:res.data[0].unit
        })
      })
    }

  },
  chooseImage: function (e) {
    var that = this;
    var images = that.data.files;
    wx.chooseImage({
      count: 6 - images.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  deleteImage: function (e) {
    var that = this;
    var images = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '系统提醒',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          images.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        that.setData({
          files: images
        });
      }
    })
  },
  uploadImg: function (e) {

    const filePath = e
    // 上传图片
    const cloudPath = "goodimg/" + (new Date()).valueOf() + filePath.match(/\.[^.]+?$/)[0]
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {
        console.log('[上传文件] 成功：', res)
        this.setData({
          uploadImgArry: this.data.uploadImgArry.concat(res.fileID)
        })
        this.setData({
          uploadImgCount: this.data.uploadImgCount + 1
        })

        console.log(this.data.uploadImgCount);
        console.log(this.data.files.length)
        if (this.data.newImgCount == this.data.uploadImgCount) {
          // this.setData({
          //   uploadImgArry: this.data.uploadImgArry.concat(res.fileID)
          // })
          this.submitCloudData()
        }   
      },
      fail: e => {
        console.error('[上传文件] 失败：', e)
        wx.showToast({
          icon: 'none',
          title: '上传失败',
        })
        wx.hideLoading();
      },
      complete: () => {
      }
    })

  },
  submitCloudData(e) {
    console.log(this.data.proGg)
    wx.cloud.callFunction({
      // 云函数名称
      name: 'product-add',
      // 传给云函数的参数
      data: {
        id:this.data.id,
        diyId:wx.getStorageSync('diyId'),
        proName: this.data.proName,
        proDetail: this.data.proDetail,
        proNowPrice: this.data.proNowPrice,
        proPrimePrice: this.data.proPrimePrice,
        proClassify: this.data.proClassify,
        proDescription: this.data.proDescription,
        proImgUrl: this.data.uploadImgArry,
        createtime: util.formatTime(new Date()),
        proGg:this.data.proGg,
        proYf:this.data.proYf,
        proPx:this.data.proPx,
        proSale:this.data.proSale,
        proState:this.data.proState,
        proUnit:this.data.proUnit
      },
      complete: res => {
        this.showSubSuccess();

        console.log('callFunction test result: ', res)
      }
    })
  },

  onClickSave() {
    if (this.data.proName == null || this.data.proName == '') {
      wx.showToast({
        title: '商品名称不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    if (this.data.proNowPrice == null || this.data.proNowPrice == '') {
      wx.showToast({
        title: '商品价格不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    wx.showLoading({
      title: '数据同步中',
    })
    console.log(this.data.files)
    for (var i = 0; i < this.data.files.length; i++) {
      if(this.data.files[i].indexOf("http://")==0){
        this.setData({
          newImgCount:this.data.newImgCount+1
        })
        
      }else{
        this.setData({
          uploadImgArry:this.data.uploadImgArry.concat(this.data.files[i])
        })
      }
    }
    for (var i = 0; i < this.data.files.length; i++) {
      if(this.data.files[i].indexOf("http://")==0)
        this.uploadImg(this.data.files[i]);
    }
    if(this.data.files.length==0||this.data.files.length==this.data.uploadImgArry.length){
      this.submitCloudData()
    }
  },
  getProName: function (e) {
    this.setData({
      proName: e.detail
    })
  },
  getProDetail: function (e) {
    this.setData({
      proDetail: e.detail
    })
  },
  getProNowPrice: function (e) {
    console.log(e)
    this.setData({
      proNowPrice: e.detail
    })
  },
  getProPrimePrice: function (e) {
    this.setData({
      proPrimePrice: e.detail
    })
  },
  getProClassify: function (e) {
    this.setData({
      proClassify: e.detail
    })
  },
  getProUnit:function(e){
    this.setData({
      proUnit: e.detail
    })
  },
  getProDescription: function (e) {
    this.setData({
      proDescription: e.detail
    })
  },
  showSubSuccess: function (e) {
    wx.showToast({
      title: '提交成功',
    })
    setTimeout(function(){
      wx.hideLoading()
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2];
      prevPage.setData({
        req: 1
      })
      wx.navigateBack()
    },1000)
    
  },
  onGoodsChange: function (e) {
    let tmp = { ggmx: '', ggsx:''}
    if(this.data.proGg.pro.length>e.detail){
      let j = this.data.proGg
      j.pro.splice(this.data.proGg.pro.length-1,1)
      this.setData({
        proGg : j
      })
    }else{
      let j = this.data.proGg
      j.pro.push(tmp)
      this.setData({
        proGg:j
      })
    }
  
  },
  onStateChange({ detail }) {
    this.setData({ proState: detail });
  },
  onPxChange(e){
    this.setData({proPx:e.detail})
  },
  onYfChange(e) {
    this.setData({ proYf: e.detail })
  },
  onGgCpsx(e){
console.log(e.detail)  
    let t = this.data.proGg
    if (e.detail == '' || e.detail == null) {
      t.con.length = 0
      t.pro[e.currentTarget.dataset.index].ggsx = ''
      this.setData({
        proGg: t
      })
      console.log(this.data.proGg)
      return
    }
    if (t.pro[e.currentTarget.dataset.index].ggmx == "" || t.pro[e.currentTarget.dataset.index].ggmx==null){
      wx.showToast({
        icon : 'none',
        title: '请输入规格明细' + e.currentTarget.dataset.index+'内容',
      })
      return
    }
    t.pro[e.currentTarget.dataset.index].ggsx = e.detail
    // for(var i=0;i<d.length;i++){
    //   t[e.currentTarget.dataset.index].ggsx.push({ property: d[i] })
    // }
    let s = false
    for(var i=0;i<t.pro.length;i++){
      if(t.pro[i].ggsx==''||t.pro[i].ggsx==null){
        s =true
      }
    }
    if(s==false){
      t.con.length = 0
      //说明要加载规格内容了
      let n = t.pro.length;
      if(n==1){
        for (var i = 0; i < t.pro[0].ggsx.split("#").length; i++) {
          let c = {name:t.pro[0].ggsx.split("#")[i],price:'',stock:''}
          t.con.push(c)
        }
      }else if(n==2){
        for (var i = 0; i < t.pro[0].ggsx.split("#").length; i++) {
            for(var j=0;j<t.pro[1].ggsx.split("#").length;j++){
              let c = { name: t.pro[0].ggsx.split("#")[i] +"-"+ t.pro[1].ggsx.split("#")[j], price: '', stock: '' }
              t.con.push(c)
            }
        }
      }else if(n==3){
        for (var i = 0; i < t.pro[0].ggsx.split("#").length; i++) {
          for (var j = 0; j < t.pro[1].ggsx.split("#").length; j++) {
              for(var k=0;k<t.pro[2].ggsx.split("#").length;k++){
                let c = { name: t.pro[0].ggsx.split("#")[i] + "-" + t.pro[1].ggsx.split("#")[j] + "-" + t.pro[2].ggsx.split("#")[k], price: '', stock: '' }
                t.con.push(c)
              }
          }
        }
      }
      
    }
    this.setData({
      proGg:t
    })
   },
  onGgCpjg(e){
    let tmp = this.data.proGg
    tmp.con[e.currentTarget.dataset.index].price = e.detail
    this.setData({
      proGg: tmp
    })
  },
  onGgCpkc(e){
    let tmp = this.data.proGg
    tmp.con[e.currentTarget.dataset.index].stock = e.detail
    this.setData({
      proGg: tmp
    })
  },
  onGgmx(e){
    let t = this.data.proGg
    t.pro[e.currentTarget.dataset.index].ggmx = e.detail
    this.setData({
      proGg: t
    })
  }
});